package com.baosight.risk.service.riri.impl;

import com.baosight.risk.api.riri.IRiaaRiskService;
import com.baosight.risk.api.xtaa.sequences.IXtaaSequencesService;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riri.RiaaRiskMapper;
import com.baosight.risk.mapper.xtaa.code.XtaaCodeMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.service.riri.entity.RiaaRisk;
import com.baosight.risk.service.riri.vo.RiaaRiskVO;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.service.xtzy.impl.XtzyCompanyServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类 名: RiaaRiskServiceImpl
 * 作 者: 黎秋荣
 * 创 建：2019年05月08日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Service
@Slf4j
public class RiaaRiskServiceImpl extends BaseServiceImpl<RiaaRisk> implements IRiaaRiskService {

    @Autowired
    private RiaaRiskMapper riaaRiskMapper;
    @Autowired
    private IXtaaSequencesService sequencesService;
    @Autowired
    private XtzyCompanyMapper companyMapper;
    @Autowired
    private XtaaCodeMapper xtaaCodeMapper;
    @Autowired
    private XtzyCompanyServiceImpl xtzyCompanyService;


    @Override
    public List<RiaaRisk> selectRiaaRisk(RiaaRiskVO riaaRisk, XtzyUser user) {
        if (StringUtils.isNotEmpty(riaaRisk.getRiskType())) {
            if (riaaRisk.getRiskType().length() > 2) {
                riaaRisk.setDetailType(riaaRisk.getRiskType());
                riaaRisk.setRiskType(null);
            }
        }
        //根据权限获取组织编码
        riaaRisk.setCompList(getCompCodes(user.getExt1(), riaaRisk.getExt5()));
        servicePage();
        return riaaRiskMapper.selectRiaaRisk(riaaRisk);
    }

    /**
     * 根据权限获取组织编码
     *
     * @param compCode
     * @param auth
     * @return
     */
    public List<String> getCompCodes(String compCode, String auth) {
        List<String> compList = new ArrayList<>();
        if (StringUtils.isNotEmpty(auth)) {
            if ("COMP".equals(auth)) {
                compList.add(compCode);
            } else if ("COMP_SUB".equals(auth)) {
                compList.add(compCode);
                //找本公司及一下公司
                XtzyCompany company = companyMapper.selectByPrimaryKey(compCode);
                if (1 != company.getPathLevel()) {
                    //并非末级，找下级子公司
                    if (1 != company.getEndLevelFlag()) {
                        List<XtzyCompany> companies = new ArrayList<>();
                        xtzyCompanyService.getNextCompany(company.getId(), companies);
                        companies.add(company);
                        compList.addAll(companies.stream().map(XtzyCompany::getId).collect(Collectors.toList()));
                    }
                }
            }
        }
        return compList;
    }


    @Override
    public Integer saveRiaaRisk(List<RiaaRiskVO> riaaRiskVOList, XtzyUser user) throws Exception {
        for (RiaaRiskVO riaaRisk : riaaRiskVOList) {
            if (StringUtils.isEmpty(riaaRisk.getRiskName())) {
                log.error("请先填写风险名称，再进行保存操作!");
                throw new Exception("请先填写风险名称，再进行保存操作!");
            }
//            if (StringUtils.isEmpty(riaaRisk.getDeptCode())){
//                log.error("请先选择组织机构，再进行保存操作!");
//                throw new Exception("请先选择组织机构，再进行保存操作!");
//            }
            //数据校验，是否已存在
            List<RiaaRisk> list = riaaRiskMapper.checkRiaaRisk(riaaRisk);
            if (CollectionUtils.isNotEmpty(list) && list.size() > 1) {
                log.error(riaaRisk.getDeptName() + "=该公司下已经存在风险名称为【" + riaaRisk.getRiskName() + "】的数据！");
                throw new Exception(riaaRisk.getDeptName() + "=该公司下已经存在风险名称为【" + riaaRisk.getRiskName() + "】的数据！");
            }
            if (StringUtils.isEmpty(riaaRisk.getId())) {
                //新增数据
                riaaRisk = (RiaaRiskVO) BeanUtils.initBean(riaaRisk);
                insertRisk(riaaRisk, user);
            } else {
                riaaRisk = (RiaaRiskVO) BeanUtils.updateBean(riaaRisk);
                updateRisk(riaaRisk);
            }
        }
        return 1;
    }

    @Override
    public List<RiaaRisk> getRiaaRiskByIds(List<String> ids) {
        return riaaRiskMapper.getRiaaRiskByIds(ids);
    }


    @Override
    public Integer insertRisk(RiaaRiskVO riaaRisk, XtzyUser user) {
        String code;
        XtaaCode xtaaCode = xtaaCodeMapper.selectByPrimaryKey(riaaRisk.getRiskType());
        riaaRisk.setRiskType(xtaaCode.getDdCode());
        riaaRisk.setRiskTypeName(xtaaCode.getDdName());
        if (StringUtils.isNotEmpty(riaaRisk.getDeptCode())) {
            XtzyCompany company = companyMapper.getCompanyInfo(riaaRisk.getDeptCode());
            //如果是公司，公司和部门是一样的，如果不是公司，找到上级公司
            if ("1".equals(company.getCompType())) {
                riaaRisk.setCompCode(riaaRisk.getDeptCode());
                riaaRisk.setCompName(riaaRisk.getDeptName());
            } else {
                company = companyMapper.getCompByCompCode(company.getPathCode());
                riaaRisk.setCompCode(company.getCompCode());
                riaaRisk.setCompName(company.getCompName());
            }
            //风险库的编码根据公司和大分类流水
            String groupFlag = "riaaRisk_" + company.getCompCode() + "_" + riaaRisk.getRiskType();
            //获得流水号
            code = sequencesService.generateCodeById(groupFlag, "riaaRisk.riskNo", company.getCompCode(), riaaRisk.getRiskType(), riaaRisk.getDetailType());

        } else {
            String compCode = "BGTA";
            String compName = "宝钢股份";
            //风险库的编码根据公司和大分类流水
            String groupFlag = "riaaRisk_" + compCode + "_" + riaaRisk.getRiskType();
            code = sequencesService.generateCodeById(groupFlag, "riaaRisk.riskNo", compCode, riaaRisk.getRiskType(), riaaRisk.getDetailType());
            riaaRisk.setCompCode(compCode);
            riaaRisk.setCompName(compName);
        }
        Integer rowOrder;
        Integer maxRowOrder = riaaRiskMapper.queryMaxRowOrder();
        if (maxRowOrder == null) {
            rowOrder = 1;
        } else {
            rowOrder = Integer.valueOf(maxRowOrder) + 1;
        }
        riaaRisk.setRowOrder(rowOrder);
        riaaRisk.setRiskNo(code);
        riaaRisk.setSubmitCompCode(user.getExt1());
        riaaRisk.setSubmitCompName(user.getExt2());
        riaaRisk.setSubmitUserCode(user.getUserCode());
        riaaRisk.setSubmitUserName(user.getUserDesc());
        return riaaRiskMapper.insert(riaaRisk);
    }

    @Override
    public Integer submitRisk(List<String> ids) {
        String status = "02";
        String statusDesc = "提交";
        //todo:调用工作流
        return riaaRiskMapper.deleteById(ids, status, statusDesc);
    }

    @Override
    public Integer updateRisk(RiaaRisk riaaRisk) {
        if (StringUtils.isNotEmpty(riaaRisk.getDeptCode())) {
            XtzyCompany company = companyMapper.getCompanyInfo(riaaRisk.getDeptCode());
            //如果是公司，公司和部门是一样的，如果不是公司，找到上级公司
            if ("1".equals(company.getCompType())) {
                riaaRisk.setCompCode(riaaRisk.getDeptCode());
                riaaRisk.setCompName(riaaRisk.getDeptName());
            } else {
                //如果公司和部门是4，或者5，找到最近父级是1得；
                company = companyMapper.getCompByCompCode(company.getPathCode());
                riaaRisk.setCompCode(company.getCompCode());
                riaaRisk.setCompName(company.getCompName());
            }
        } else {
            riaaRisk.setCompCode("BGTA");
            riaaRisk.setCompName("宝钢股份");
        }
        return riaaRiskMapper.updateByPrimaryKeySelective(riaaRisk);
    }

    @Override
    public Integer deleteById(List<String> ids, String status) {
        String statusDesc;
        if ("10".equals(status)) {
            statusDesc = "有效";
        } else {
            statusDesc = "停用";
        }
        return riaaRiskMapper.deleteById(ids, status, statusDesc);
    }

    @Override
    public void updateRowOrder(RiaaRiskVO riaaRisk, XtzyUser user) {
        if (StringUtils.isNotEmpty(riaaRisk.getRiskType())) {
            if (riaaRisk.getRiskType().length() > 2) {
                riaaRisk.setDetailType(riaaRisk.getRiskType());
                riaaRisk.setRiskType(null);
            }
        }
        riaaRisk.setCompList(getCompCodes(user.getExt1(), riaaRisk.getExt5()));
        List<String> ids = riaaRiskMapper.selectRiaaRisk(riaaRisk).stream().map(RiaaRisk::getId).collect(Collectors.toList());
        RiaaRisk riaa = get(riaaRisk.getId());
        int i = ids.indexOf(riaaRisk.getId());
        if("up".equals(riaaRisk.getExt2())){
            i--;
        } else {
            i++;
        }
        if(i < ids.size() && i >= 0){
            RiaaRisk riaaNext = get(ids.get(i));
            Integer rowOrder1 = riaa.getRowOrder();
            Integer rowOrder2 = riaaNext.getRowOrder();
            riaa.setRowOrder(rowOrder2);
            update(riaa);
            riaaNext.setRowOrder(rowOrder1);
            update(riaaNext);
        }

    }

}
